import { AnyAction } from "redux";
import * as types from "../action-types";
import { Slider } from "../../typings/slider";
import Dog from "@/typings/dog";

export interface Dogs{
  loading: boolean;
  list: Dog[];
  hasMore: boolean;
  offset: number;
  limit: number;
}

export interface HomeState {
  name: string;
  currentCategory: string;
  sliders: Slider[];
  dogs:Dogs;
}

let initialState: HomeState = {
  name: "home",
  currentCategory: "全部",
  sliders: [],
  dogs:{
    loading:false,
    list:[],
    hasMore:true,
    offset:0,
    limit:5
  }
};

const reducer = function (state: HomeState = initialState, action: AnyAction) {
  switch (action.type) {
    case types.SET_CURRENT_CATEGORY:
      return { ...state, ...{ currentCategory: action.payload } };
    case types.GET_SLIDERS:
      if (!action.payload.data) break;
      return { ...state, ...{ sliders: action.payload.data } };
    case types.SET_DOGS_LOADING:
      return {...state,dogs:{...state.dogs,loading:action.payload}};
    case types.SET_DOGS:
      if(!action.payload) break;
      return {...state,dogs:{...state.dogs
        ,loading:false
        ,hasMore:action.payload.hasMore,
        list:[...state.dogs.list,...action.payload.list],
        offset:state.dogs.offset+action.payload.list.length 
      },
      }
     case types.REFRESH_DOGS:
       return{
         ...state,
         dogs:{
           ...state.dogs,
           loading:false,
           hasMore:action.payload.hasMore,
           list:action.payload.list,
           offset:action.payload.list.length,
         }
       } 
    default:
      return state;
  }
  return state;
};
export default reducer;
